package com.demo.base.exception;

import com.demo.base.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 曳戈泰尔
 * @version 1.0
 * @description 全局异常捕获处理
 * @date 2023/3/13 1:59 PM
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /** 定义参数校验异常处理 提示后缀 */
    private static final String BAD_REQUEST_MSG = " Check failed";

    /**
     * 处理空指针的异常
     *
     * @param e 异常
     * @return 请求异常处理Response
     */
    @ExceptionHandler(value = NullPointerException.class)
    public Result<Object> nullPointExceptionHandler(NullPointerException e) {
        log.error("发生空指针异常！原因是：{}", e.getMessage());

        return Result.fail(e.getMessage());
    }

    /**
     * 处理业务异常，自定义异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(AiException.class)
    public Result<Object> baseExceptionHandler(AiException e) {
        log.error("捕获自定义异常！原因是：{}", e.getMessage());

        return Result.fail(e.getMessage());
    }

    /**
     * 处理请求参数异常
     *
     * @param e 请求参数异常
     * @return Result
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result<Object> missingServletRequestParameterExceptionHandler(
            MissingServletRequestParameterException e) {
        return Result.fail(e.getParameterName() + BAD_REQUEST_MSG);
    }

    /**
     * 处理 json 请求体调用接口校验失败抛出的异常
     *
     * @param e json请求体调用接口校验失败抛出的异常
     * @return Result
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Object> methodArgumentNotValidExceptionHandler(
            MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        List<String> collect =
                fieldErrors.stream()
                        .map(DefaultMessageSourceResolvable::getDefaultMessage)
                        .collect(Collectors.toList());
        return Result.fail(ExceptionCodeEnum.sys_0003.getCode(), collect.toString());
    }

    /**
     * 处理 form data方式调用接口校验失败抛出的异常
     *
     * @param e form data方式调用接口校验失败抛出的异常
     * @return Result
     */
    @ExceptionHandler(BindException.class)
    public Result<Object> bindExceptionHandler(BindException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        List<String> collect =
                fieldErrors.stream()
                        .map(DefaultMessageSourceResolvable::getDefaultMessage)
                        .collect(Collectors.toList());
        return Result.fail(ExceptionCodeEnum.sys_0003.getCode(), collect.toString());
    }

    /**
     * 处理单个参数校验失败抛出的异常
     *
     * @param e 单个参数校验失败抛出的异常
     * @return Result
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result<Object> constraintViolationExceptionHandler(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        List<String> collect =
                constraintViolations.stream()
                        .map(ConstraintViolation::getMessage)
                        .collect(Collectors.toList());
        return Result.fail(ExceptionCodeEnum.sys_0003.getCode(), collect.toString());
    }

    /**
     * 处理其他异常
     *
     * @param e 异常
     * @return 请求异常处理Response
     */
    @ExceptionHandler(value = Exception.class)
    public Result<Object> exceptionHandler(Exception e) {
        log.error("未知异常！原因是：{}", e.getMessage());

        return Result.fail(e.getMessage());
    }
}
